package cn.bugstack.infrastructure.adapter.port;

import cn.bugstack.domain.trade.adapter.port.ITradePort;
import cn.bugstack.domain.trade.model.entity.NotifyTaskEntity;
import cn.bugstack.domain.trade.model.valobj.NotifyTypeEnumVO;
import cn.bugstack.infrastructure.event.EventPublisher;
import cn.bugstack.infrastructure.gateway.GroupBuyNotifyService;
import cn.bugstack.infrastructure.redis.IRedisService;
import cn.bugstack.types.enums.NotifyTaskHTTPEnumVO;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author liuxinzhi
 * @description:
 * @date 2025/8/11 11:57
 */
@Service
public class TradePort implements ITradePort {

    @Resource
    GroupBuyNotifyService groupBuyNotifyService;

    @Resource
    IRedisService redisService;

    @Resource
    private EventPublisher eventPublisher;

    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTask) {
        // 可能部署多台实例，所以需要加锁保证线程安全
        RLock lock = redisService.getLock(notifyTask.lockKey());
        try {
            try {
                if (lock.tryLock(3, 0, TimeUnit.SECONDS)) {
                    // HTTP方式回调
                    if(NotifyTypeEnumVO.HTTP.getCode().equals(notifyTask.getNotifyType())){
                        if (StringUtils.isBlank(notifyTask.getNotifyUrl()) || "暂无".equals(notifyTask.getNotifyUrl())) {
                            return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                        }
                        return groupBuyNotifyService.groupBuyNotify(notifyTask.getNotifyUrl(), notifyTask.getParameterJson());
                    }
                    // MQ方式回调
                    if(NotifyTypeEnumVO.MQ.getCode().equals(notifyTask.getNotifyType())){
                        eventPublisher.publish(notifyTask.getNotifyMQ(), notifyTask.getParameterJson());
                        return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                    }

                }
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } catch (Exception e) {
            Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }
        return NotifyTaskHTTPEnumVO.NULL.getCode();
    }
}
